﻿using System.Linq;
using System.Windows;
using System.Collections.Generic;
using System.Windows.Media;
using DeepEarth.Core.Utilities;

namespace DeepEarth.Map.Core.Utilities
{
    public static class VisualTree
    {
        public static T FindAncestor<T>(DependencyObject element) where T : class
        {
            if (element is T)
            {
                return element as T;
            }

            DependencyObject parent = VisualTreeHelper.GetParent(element);
            if (parent != null)
            {
                return FindAncestor<T>(parent);
            }
            else
            {
                return null;
            }
        }

        public static IEnumerable<DependencyObject> FindAllChildren(DependencyObject element)
        {
            List<DependencyObject> children = new List<DependencyObject>();
            int count = VisualTreeHelper.GetChildrenCount(element);

            for (int i = 0; i < count; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(element, i);
                children.AddRange(child.Concat(FindAllChildren(child)));
            }

            return children;
            
        }

        public static IEnumerable<T> FindAllChildren<T>(DependencyObject element)
        {
            return FindAllChildren(element).OfType<T>();
        }
    }

}
